package com.zjcode.cdcer.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.chinatechstar.component.commons.supports.PageData;
import com.chinatechstar.component.commons.utils.UuidUtil;
import com.zjcode.cdcer.mapper.TkmGastroscopeDiagnosisCollectInfoMapper;
import com.zjcode.cdcer.mapper.TkmGastroscopeDiagnosisInfoMapper;
import com.zjcode.cdcer.model.SysOrg;
import com.zjcode.cdcer.model.TkmGastroscopeDiagnosisCollectInfo;
import com.zjcode.cdcer.model.TkmGastroscopeDiagnosisInfo;
import com.zjcode.cdcer.model.TkmUserOrgAndRegions;
import com.zjcode.cdcer.service.SysUserService;
import com.zjcode.cdcer.service.TkmGastroscopeDiagnosisInfoService;
import com.zjcode.cdcer.service.TkmSysUserService;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ClassName:TkmGastroscopeDiagnosisInfoServiceImpl
 * @功能：
 * @author：wlei
 * @日期：2022/7/27-00:39
 **/
@Service
@Slf4j
public class TkmGastroscopeDiagnosisInfoServiceImpl implements TkmGastroscopeDiagnosisInfoService {

    @Autowired
    private TkmGastroscopeDiagnosisInfoMapper gastroscopeDiagnosisInfoMapper;
    @Autowired
    private TkmGastroscopeDiagnosisCollectInfoMapper gastroscopeDiagnosisCollectInfoMapper;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private TkmSysUserService tkmSysUserService;

    private static final List<String> MONTHS = Arrays.asList("一",
                                                             "二",
                                                             "三",
                                                             "四",
                                                             "五",
                                                             "六",
                                                             "七",
                                                             "八",
                                                             "九",
                                                             "十",
                                                             "十一",
                                                             "十二");

    /**
     * 查询所有
     *
     * @param pageData
     * @return
     */
    @Override
    public List<TkmGastroscopeDiagnosisInfo> listAll(PageData pageData) {

        List<TkmGastroscopeDiagnosisInfo> result = new ArrayList<>();

        String userId = (String) pageData.get("user");
        String year = (String) pageData.get("year");

        // 获取extFlag
        String extFlag = sysUserService.findUserExtFlag(userId);
        pageData.put("extFlag", extFlag);

        List<TkmGastroscopeDiagnosisInfo> list = gastroscopeDiagnosisInfoMapper.selectAllByUploadYearAndExtFlagOrderByUploadMonth(
            year,
            extFlag);

        // 初始化12个月份的数据
        for (int i = 1; i <= 12; i++) {
            TkmGastroscopeDiagnosisInfo each = new TkmGastroscopeDiagnosisInfo();
            int finalI = i;
            Optional<TkmGastroscopeDiagnosisInfo> first = list
                .stream()
                .filter(item -> {
                    int uploadMonth = item.getUploadMonth();
                    return uploadMonth == finalI;
                })
                .findFirst();

            if (first.isPresent()) {
                TkmGastroscopeDiagnosisInfo source = first.get();
                BeanUtils.copyProperties(source, each);
                each.setUploadMonthText(MONTHS.get(i - 1));
            } else {
                each.setUploadYear(year);
                each.setUploadMonth(i);
                each.setUploadMonthText(MONTHS.get(i - 1));
            }
            result.add(each);
        }

        return result;
    }

    @Override
    public int updateRecords(PageData pageData) {

        String json = (String) pageData.get("records");
        String userId = (String) pageData.get("user");
        List<TkmGastroscopeDiagnosisInfo> list = JSONObject.parseArray(json,
                                                                       TkmGastroscopeDiagnosisInfo.class);

        String extFlag = sysUserService.findUserExtFlag(userId);

        // 读取用户所在的机构信息
        TkmUserOrgAndRegions orgAndRegions = tkmSysUserService.findUserRegionsAndOrg(userId);
        SysOrg sysOrg = orgAndRegions.getSysOrg();

        // 过滤调不能进行写入的数据
        if (list != null) {
            list.removeIf(each -> {
                Integer amounts = each.getAmounts();
                String envienceFilePath = each.getEnvienceFilePath();
                String envienceFileUrl = each.getEnvienceFileUrl();
                return amounts == null && envienceFilePath == null && envienceFileUrl == null;
            });
            // 数据过滤完成后,对数据进行插入,或更新操作
            List<TkmGastroscopeDiagnosisInfo> insertList = new ArrayList<>();
            List<TkmGastroscopeDiagnosisInfo> updateList = new ArrayList<>();
            list
                .stream()
                .forEach(each -> {
                    String id = each.getId();
                    if (id == null) {
                        // 插入新数据
                        each.setId(UuidUtil.get32UUID());
                        each.setAuditStatus(0);
                        each.setIsHaveError(0);
                        each.setErrorMessage("");
                        each.setCreateBy(userId);
                        each.setDeleted(0);
                        each.setVersion(1);
                        each.setInsertDatetime(new Date(System.currentTimeMillis()));
                        each.setLastUpdateDatetime(new Date(System.currentTimeMillis()));
                        each.setRemarks("");
                        each.setExtFlag(extFlag);
                        each.setExtFlag2("");
                        each.setOrgId(sysOrg
                                          .getId()
                                          .toString());
                        each.setProvinceName(sysOrg.getProvinceName());
                        each.setCityName(sysOrg.getCityName());
                        each.setRegionName(sysOrg.getRegionName());
                        // 此处执行sql写入
                        insertList.add(each);
                    } else {
                        // 更新数据
                        // 获取原始数据
                        TkmGastroscopeDiagnosisInfo source = gastroscopeDiagnosisInfoMapper.selectByPrimaryKey(
                            id);
                        source.setAmounts(each.getAmounts() == null ? 0 : each.getAmounts());
                        source.setEnvienceFilePath(each.getEnvienceFilePath());
                        source.setEnvienceFileUrl(each.getEnvienceFileUrl());
                        source.setOrgId(sysOrg
                                            .getId()
                                            .toString());
                        source.setProvinceName(sysOrg.getProvinceName());
                        source.setCityName(sysOrg.getCityName());
                        source.setRegionName(sysOrg.getRegionName());
                        source.setLastUpdateDatetime(new Date(System.currentTimeMillis()));
                        Integer auditStatus = each.getAuditStatus();
                        if (auditStatus != 1) {
                            // 非审核通过的状态,都设置为待审核
                            source.setAuditStatus(0);
                        }

                        updateList.add(source);
                    }

                });
            // 执行插入操作
            if (insertList.size() > 0) {
                gastroscopeDiagnosisInfoMapper.insertList(insertList);
            }
            // 执行编辑操作
            if (updateList.size() > 0) {
                updateList
                    .stream()
                    .forEach(each -> {
                        gastroscopeDiagnosisInfoMapper.updateByPrimaryKey(each);
                    });
            }
            // 将数据写入汇总信息表中

            // 获取当前的年份
            String uploadYear = list
                .get(0)
                .getUploadYear();

            // 获取用户所在机构今年上报的所有数据
            List<TkmGastroscopeDiagnosisInfo> diagnosisInfos = gastroscopeDiagnosisInfoMapper.selectAllByUploadYearAndExtFlagOrderByUploadMonth(
                uploadYear,
                extFlag);

            // 删除今年的数据
            gastroscopeDiagnosisCollectInfoMapper.deleteByUploadYearAndOrgId(uploadYear,
                                                                             sysOrg
                                                                                 .getId()
                                                                                 .toString());
            // 重新插入今年的数据
            TkmGastroscopeDiagnosisCollectInfo diagnosisCollectInfo = getGastroscopeDiagnosisCollectInfo(
                userId,
                sysOrg,
                uploadYear,
                extFlag,
                diagnosisInfos);
            gastroscopeDiagnosisCollectInfoMapper.insert(diagnosisCollectInfo);

            log.info(diagnosisCollectInfo.toString());

            return list.size();
        } else {
            return 0;
        }

    }

    /**
     * 获取诊断汇总实体
     *
     * @param userId
     * @param sysOrg
     * @param uploadYear
     * @param extFlag
     * @param diagnosisInfos
     * @return
     */
    private TkmGastroscopeDiagnosisCollectInfo getGastroscopeDiagnosisCollectInfo(String userId,
                                                                                  SysOrg sysOrg,
                                                                                  String uploadYear,
                                                                                  String extFlag,
                                                                                  List<TkmGastroscopeDiagnosisInfo> diagnosisInfos) {
        TkmGastroscopeDiagnosisCollectInfo diagnosisCollectInfo = new TkmGastroscopeDiagnosisCollectInfo();
        diagnosisCollectInfo.setId(UuidUtil.get32UUID());
        diagnosisCollectInfo.setUploadYear(uploadYear);
        diagnosisCollectInfo.setUploadMonth(null);
        diagnosisCollectInfo.setOrgId(sysOrg
                                          .getId()
                                          .toString());
        diagnosisCollectInfo.setOrgName(sysOrg.getOrgName());
        diagnosisCollectInfo.setProvinceName(sysOrg.getProvinceName());
        diagnosisCollectInfo.setProvinceCode(sysOrg.getProvinceCode());
        diagnosisCollectInfo.setCityName(sysOrg.getCityName());
        diagnosisCollectInfo.setCityCode(sysOrg.getCityCode());
        diagnosisCollectInfo.setRegionName(sysOrg.getRegionName());
        diagnosisCollectInfo.setRegionCode(sysOrg.getRegionCode());
        diagnosisCollectInfo.setJanCount(String.valueOf(getTotalCountByMonth(diagnosisInfos, 1)));
        diagnosisCollectInfo.setFebCount(String.valueOf(getTotalCountByMonth(diagnosisInfos, 2)));
        diagnosisCollectInfo.setMarCount(String.valueOf(getTotalCountByMonth(diagnosisInfos, 3)));
        diagnosisCollectInfo.setAprCount(String.valueOf(getTotalCountByMonth(diagnosisInfos, 4)));
        diagnosisCollectInfo.setMayCount(String.valueOf(getTotalCountByMonth(diagnosisInfos, 5)));
        diagnosisCollectInfo.setJunCount(String.valueOf(getTotalCountByMonth(diagnosisInfos, 6)));
        diagnosisCollectInfo.setJulCount(String.valueOf(getTotalCountByMonth(diagnosisInfos, 7)));
        diagnosisCollectInfo.setAugCount(String.valueOf(getTotalCountByMonth(diagnosisInfos, 8)));
        diagnosisCollectInfo.setSeptCount(String.valueOf(getTotalCountByMonth(diagnosisInfos, 9)));
        diagnosisCollectInfo.setOctCount(String.valueOf(getTotalCountByMonth(diagnosisInfos, 10)));
        diagnosisCollectInfo.setNovCount(String.valueOf(getTotalCountByMonth(diagnosisInfos, 11)));
        diagnosisCollectInfo.setDecCount(String.valueOf(getTotalCountByMonth(diagnosisInfos, 12)));
        diagnosisCollectInfo.setExtFlag(extFlag);
        diagnosisCollectInfo.setExtFlag2("");
        diagnosisCollectInfo.setCreateBy(userId);
        diagnosisCollectInfo.setDeleted(0);
        diagnosisCollectInfo.setVersion(1);
        diagnosisCollectInfo.setInsertDatetime(new Date(System.currentTimeMillis()));
        diagnosisCollectInfo.setLastUpdateDatetime(new Date(System.currentTimeMillis()));
        diagnosisCollectInfo.setRemarks("");
        return diagnosisCollectInfo;
    }

    /**
     * 按照月份,获取该月份下内镜拍摄个数
     *
     * @param diagnosisInfos
     * @param month
     * @return
     */
    private int getTotalCountByMonth(List<TkmGastroscopeDiagnosisInfo> diagnosisInfos, int month) {
        Optional<TkmGastroscopeDiagnosisInfo> first = diagnosisInfos
            .stream()
            .filter(each -> {
                int uploadMonth = each.getUploadMonth();
                return uploadMonth == month;
            })
            .findFirst();
        if (first.isPresent()) {
            TkmGastroscopeDiagnosisInfo tkmGastroscopeDiagnosisInfo = first.get();
            return tkmGastroscopeDiagnosisInfo.getAmounts() == null ? 0
                : tkmGastroscopeDiagnosisInfo.getAmounts();
        } else {
            return 0;
        }
    }
}
